package com.cracker.sso.listener;

import com.cracker.sso.config.AppConfig;
import com.cracker.sso.dao.TokenDao;
import com.cracker.sso.event.UserLoginEvent;
import com.cracker.sso.model.TokenModel;
import com.cracker.sso.model.UserModel;
import com.cracker.sso.tool.AuthTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserLoginEventListener {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private AuthTool authTool;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private AppConfig appConfig;

    @EventListener
    public void userLoginEvent(UserLoginEvent event) {
        UserModel userModel = event.getUserModel();
        log.warn("用户登录 {}", userModel);
    }

    @EventListener
    public void generalLoginToken(UserLoginEvent event) {
        UserModel userModel = event.getUserModel();
        String token = authTool.generalToken();
        userModel.setToken(token);
        Cookie cookie = new Cookie("TGT-COOKIE", token);
        if (!StringUtils.isEmpty(appConfig.getTokenDomain())) {
            cookie.setDomain(appConfig.getTokenDomain());
        }
        response.addCookie(cookie);
        TokenModel tokenModel = new TokenModel();
        tokenModel.setToken(token);
        tokenModel.setUser(userModel);
        tokenDao.save(tokenModel);
    }
}
